from typing import Optional, Dict, List
from fastapi import WebSocket
import socket
import requests
import struct


class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, web_socket: WebSocket):
        await web_socket.accept()
        self.active_connections.append(web_socket)

    def disconnect(self, web_socket: WebSocket):
        self.active_connections.remove(web_socket)

    async def send_data(self, message: str, web_socket: WebSocket):
        await web_socket.send_text(message)

    async def recv_data(self, web_socket: WebSocket):
        res = await web_socket.receive_text()
        return res

    def len_connect(self):
        return len(self.active_connections)


class TianXingApi:

    def __init__(self, key: Optional[str] = '5651271c72f37953a55caff8d70705a7', encoding: Optional[str] = 'utf-8'):
        self.__KEY = key
        self.__ENCODER = encoding

    def getWeather(self, city: Optional[str]):
        params_dict = {'key': self.__KEY, 'city': city}
        res = requests.get(url='http://api.tianapi.com/txapi/tianqi/index', params=params_dict)
        res.encoding = self.__ENCODER
        if res.status_code != 200:
            return None
        else:
            return res.json()


class MobileHeartBeat:

    def __init__(self):
        self.__connected_devs: Dict[str] = {}

    def push_dev(self, user_agent: str, now_time: float):
        # print(user_agent)
        self.__connected_devs[user_agent] = {'last_time': now_time}

    def remove_dev(self, user_agent: str):
        self.__connected_devs.pop(user_agent)

    def len_mobile_connect(self):
        return len(self.__connected_devs)

    def clear_dev(self):
        self.__connected_devs.clear()

    def _get_connected_devs(self):
        return self.__connected_devs


if __name__ == '__main__':
    structPack = struct.Struct("<s")
    address = ('0.0.0.0', 8266)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(address)
    s.listen(5)

    print("开始监听")
    ss, addr = s.accept()
    print("接收到客户端连接")
    # while True:
    # bin_data = structPack.pack(b"HelloWorld")
    while True:
        res = ss.recv(1024)
        data = str(input("data:"))
        ss.send(data.encode())
        # time.sleep(1)
        print(res.decode())
